package com.study.servlet.cookie.prac01;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* @Name: LoginServlet
* @Description: Cookie应用：记住用户名
* @Author: 李超	lc_jack@foxmail.com
* @CreateDate: 2017-3-1 下午9:19:10 
* @Version: V1.0
 */
public class LoginServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//设置响应编码
		response.setContentType("text/html;charset=UTF-8") ;
		PrintWriter out = response.getWriter() ;
		//获取登录信息
		request.setCharacterEncoding("UTF-8") ; //设置请求信息编码，适用于Post方式提交
		String username = request.getParameter("username") ;
		String password = request.getParameter("password") ;
		String remeber = request.getParameter("remeber") ;
		if("admin".equals(username) && "admin".equals(password)) {
			//创建Cookie
			Cookie cookie = new Cookie("username", username) ;
			cookie.setPath(request.getContextPath()) ; //扩大Cookie访问路径范围
			if(remeber != null && !"".equals(remeber)) {
				cookie.setMaxAge(Integer.MAX_VALUE) ; //保存Cookie到浏览器
			} else {
				cookie.setMaxAge(0) ; //不保存
			}
			//写回
			response.addCookie(cookie) ;
			out.write("登录成功！！！") ;
		} else {
			response.setHeader("Refresh", "2;URL=/java-servlet/servlet/LoginServlet") ;
			out.write("对不起，登录失败！！！") ;
		}
		out.close() ;
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}

}
